﻿using UnityEngine;
using System.Collections;

namespace edit{
	public class Block : MonoBehaviour {
		// 显示对话框时隐藏label
		public static bool hideCountLabel = false;
		// 拖放初始化
		public Sprite[] sprites;
		// 用于保存数据，Main也会修改它
		public int currIndex = 0;

		Main main;
		SpriteRenderer spriteRenderer;
		Vector3 pos;
		GUIStyle style;

		int lastIndex = -1;

		// Use this for initialization
		void Start () {
			main = Camera.main.transform.GetComponent<Main>();
			pos = transform.position;
			spriteRenderer = transform.GetComponent<SpriteRenderer> ();
			style = new GUIStyle ();
			//style.normal.textColor = new Color (255, 255, 255);
			style.fontSize = 20;

			spriteRenderer.sprite = sprites[currIndex];
			lastIndex = currIndex;
			if (main.counts [currIndex] > 0) {
				main.counts [currIndex]--;
			}
		}

		void OnMouseDown() {
			// 有改动
			Main.hasSaved = false;
			while (true) {
				currIndex++;
				currIndex = currIndex % sprites.Length;
				if (main.counts [currIndex] != 0) {	// 跳过0
					break;
				}
			}
			if (main.counts [currIndex] > 0) {
				main.counts [currIndex]--;
			}

			if (lastIndex != -1 && main.counts[lastIndex] > -1) {
				main.counts[lastIndex]++;
			}
			spriteRenderer.sprite = sprites[currIndex];
			lastIndex = currIndex;
			// 修改数组 (j + 1) * 2 - 1, (i + 1) * 2 - 1
			main.map [(int)(pos.y + 1) / 2 - 1, (int)(pos.x + 1) / 2 - 1] = Main.index2code[currIndex];
//print (((int)(pos.y + 1) / 2 - 1) + ", " + ((int)(pos.x + 1) / 2 - 1) + " = " + Main.index2code [currIndex]);
		}

		void OnGUI() {
			if (hideCountLabel) {
				return;
			}

			int w = Screen.width;
			int h = Screen.height;
			int gridSize = w / 13;
			int count = main.counts [currIndex];

			if (count > -1) {
				GUI.Label(new Rect((pos.x + 1) / 2 * gridSize - 10, h - 20 - (pos.y - 1) / 2 * gridSize, 10, 20),
				          count + "",
				          style);
			}
		}
		
		// Update is called once per frame
		void Update () {
			
		}
	}
}